/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.danlu.widget.holder.ReceiveAddressItemHolder;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.DelDeliverAddressReqeust;
import cn.com.hd.mall.web.webservices.entity.request.mydl.deliveraddr.SetDefaultDeliverAddressRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.deliveraddr.DeliverAddressListReponse;
import cn.com.hd.mall.web.webservices.entity.response.mydl.deliveraddr.DeliverAddressListReponse.DeliverAddressListModel;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-13 10:32<br/>
 *
 * <p>
 * 我的收货地址画面  我的丹露---收货地址管理
 * </p>
 */
public class MyReceiveAddressActivity extends BaseActivity implements OnClickListener {
    /**
     * 丹露用异步任务代理
     */
    // private DanluTaskProxy danluTaskProxy;
    /**
     * 收货地址数据接收
     */
    private DeliverAddressListReponse addressListReponse;
    /**
     * 获取收货地址数据请求
     */
    private BaseRequest form;
    /**
     * 收货地址数据模型
     */
    private DeliverAddressListModel addressModel;
    /**
     * 收货地址UI元素List
     */
    private List<ReceiveAddressItemHolder> receiveAddressItemHolders;
    /**
     * 下拉刷新容器
     */
    private PtrClassicFrameLayout ptrdd;
    /**
     * LayoutInflater。
     */
    private LayoutInflater layoutInflater;
    /**
     * 收货地址列表容器
     */
    private LinearLayout llytAddressContainer;
    /**
     * 有收货地址列表
     */
    private LinearLayout llytHasData;
    /**
     * 无收货地址列表
     */
    private LinearLayout llytNoData;
    private boolean setDefauFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 实例化画面控件
        //        getDelegate ().setContentView (R.layout.layout_my_address, R.my_address.class);
        setContentView(R.layout.activity_my_receive_address);
        init();
        ptrdd.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        frame.refreshComplete();
                    }
                }, 2000);
            }
        });
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 页面初始化
     */
    private void init() {
        ptrdd = (PtrClassicFrameLayout) findViewById(R.id.ptrdd);
        llytAddressContainer = (LinearLayout) findViewById(R.id.llytAddressContainer);
        llytHasData = (LinearLayout) findViewById(R.id.llytHasData);
        llytNoData = (LinearLayout) findViewById(R.id.llytNoData);
        // 初始化LayoutInflater
        layoutInflater = LayoutInflater.from(this);
        form = new BaseRequest();
        getDeliverAddressList(); // 获取收货地址
        // 添加收货地址监听
        Button receiveAddBtn = (Button) findViewById(R.id.receiveAddBtn);
        receiveAddBtn.setOnClickListener(this);
    }

    /**
     * 获取收货地址
     */
    private void getDeliverAddressList() {
        // 设置参数：会话验证标识
        form.setToken(agent.getToken());
        // 获取收货地址
        agent.getApi().getDeliveryAddressList(form).compose(OperatorUtils.<DeliverAddressListReponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<DeliverAddressListReponse>(MyReceiveAddressActivity.this, true, R.string.loading_common_msg, false) {
                    @Override
                    protected void onSuccess(DeliverAddressListReponse deliverAddressListReponse) {
                        refreshUI(deliverAddressListReponse);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        showNoDataView();
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "收货地址获取失败！" : displayMessage);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        int index;

        switch (v.getId()) {
            case R.id.receiveAddBtn:
                // 跳转添加收货地址页面
                startReceiveAddressAddPage(null);
                break;

            case R.id.setDefauReceive:   //设为默认
                index = (Integer) v.getTag();
                // 设为默认收货地址
                if (getSelectDeliverAddressModel(index).getIsDefault().equals("1")) {

                    setDefaultAddress(getSelectDeliverAddressModel(index).getAddressId());
                }
                break;

            case R.id.editReceive:
                index = (Integer) v.getTag();
                // 跳转添加收货地址页面
                startReceiveAddressAddPage(getSelectDeliverAddressModel(index));
                break;

            case R.id.deleteReceive:
                index = (Integer) v.getTag();
                // 删除收货地址
                createReceiveDeleteDialog(getSelectDeliverAddressModel(index).getAddressId());
                break;

            default:
                break;
        }

    }

    /**
     * 跳转添加/编辑收货地址页面
     */
    public void startReceiveAddressAddPage(DeliverAddressListModel modle) {
        Intent intent = new Intent();
        intent.setClass(MyReceiveAddressActivity.this, MyReceiveAddressAddActivity.class);
        if (modle == null) {
            intent.putExtra("RECEIVE", 0);
        } else {
            intent.putExtra("RECEIVE", 1);
            intent.putExtra("PRIV", modle.getAreaProvinceName());
            intent.putExtra("CITY", modle.getAreaCityName());
            intent.putExtra("DIST", modle.getAreaDistrictName());
            intent.putExtra("PRIVCO", modle.getAreaProvinceCode());
            intent.putExtra("CITYCO", modle.getAreaCityCode());
            intent.putExtra("DISTCO", modle.getAreaDistrictCode());
            intent.putExtra("PERSON", modle.getDeliverPerson());
            intent.putExtra("MOBOL", modle.getDeliverMobile());
            intent.putExtra("DETAIL", modle.getAddressDetail());
            intent.putExtra("ADDID", modle.getAddressId());
            intent.putExtra("ISDEFAU", modle.getIsDefault());

        }
        startActivityForResult(intent, 100);
    }

    /**
     * 获取点击的数据
     */
    private DeliverAddressListModel getSelectDeliverAddressModel(int index) {
        if (addressListReponse.getDeliverAddressModelList().size() > 0) {
            for (int i = 0; i < addressListReponse.getDeliverAddressModelList().size(); i++) {
                if (index == i) {
                    addressModel = addressListReponse.getDeliverAddressModelList().get(index);
                }
            }
        }
        return addressModel;
    }

    /**
     * 设为默认地址
     *
     * @param deliverAddressId
     *         收货地址id
     */
    private void setDefaultAddress(String deliverAddressId) {
        SetDefaultDeliverAddressRequest form = new SetDefaultDeliverAddressRequest();
        form.setToken(agent.getToken());
        form.setDeliverAddressId(deliverAddressId);
        agent.getApi().setDefaultDeliverAddress(form).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(MyReceiveAddressActivity.this, true, R.string.tips_change_default_address, false) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        getDeliverAddressList();
                        if (setDefauFlag) {
                            setDefauFlag = false;
                        } else {
                            ToastUtil.getInstance().show(R.string.set_sucess);
                        }
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        if (code.equals("1")) {
                            displayMsg = getString(R.string.add_shopping_cart_error_1);
                        } else if (code.equals("2")) {
                            displayMsg = getString(R.string.del_failed);
                            getDeliverAddressList();
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? "默认地址设置失败！" : displayMessage);
                    }
                });
    }

    /**
     * 创建删除收货地址对话框
     *
     * @param deliverAddressId
     *         收货地址id
     */
    private void createReceiveDeleteDialog(final String deliverAddressId) {
        // 创建Builder
        //        ViewDialog.Builder builder = new ViewDialog.Builder(getDelegate().getContext());
        ViewDialog.Builder builder = new ViewDialog.Builder(MyReceiveAddressActivity.this);
        // 设置标题
        builder.setTitle(R.string.prompt_label);
        // 设置信息
        TextView msgTextView = new TextView(this);
        msgTextView.setText(R.string.receive_address_dialog_msg);
        msgTextView.setGravity(Gravity.CENTER_HORIZONTAL);
        msgTextView.setTextColor(Color.BLACK);
        builder.setContentView(msgTextView);
        // 设置Positive按钮点击监听
        builder.setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 删除收货地址
                delAddress(deliverAddressId);
                // 对话框关闭
                dialog.dismiss();
            }
        });

        // 设置Negative按钮点击监听
        builder.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                // 对话框关闭
                dialog.dismiss();
            }
        });
        // 创建对话框并显示
        builder.create().show();
    }

    /**
     * 删除收货地址
     *
     * @param deliverAddressId
     *         收货地址id
     */
    private void delAddress(String deliverAddressId) {
        // 删除收货地址数据请求
        DelDeliverAddressReqeust delDeliverAddressReqeust = new DelDeliverAddressReqeust();
        delDeliverAddressReqeust.setToken(agent.getToken());
        delDeliverAddressReqeust.setDeliverAddressId(deliverAddressId);
        agent.getApi().delDeliverAddress(delDeliverAddressReqeust).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(MyReceiveAddressActivity.this, true, R.string.tips_del, false) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        ToastUtil.getInstance().show(R.string.del_sucess);
                        getDeliverAddressList();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        if (code.equals("2")) {
                            displayMsg = getString(R.string.del_checked_error);
                        } else {
                            displayMsg = getString(R.string.del_fail);
                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                if (data != null) {
                    if (data.getStringExtra("ADDRESID") != null && data.getStringExtra("ISDEFAU") != null) {
                        String addressId = data.getStringExtra("ADDRESID");
                        String isDeafu = data.getStringExtra("ISDEFAU");

                        if (isDeafu.equals("0")) {
                            setDefauFlag = true;
                            setDefaultAddress(addressId);
                        } else {
                            getDeliverAddressList();
                        }

                    } else {
                        getDeliverAddressList();
                    }
                }
                break;

            default:
                break;
        }
    }

    /**
     * 更新UI显示
     */
    private void refreshUI(DeliverAddressListReponse result) {
        addressListReponse = result;
        if (result.getDeliverAddressModelList() != null && result.getDeliverAddressModelList().size() > 0) {
            buildReceiveAddList(result);
            showHasDataView();
        } else {
            showNoDataView();
        }
    }

    /**
     * 构建收货地址列表
     */
    private void buildReceiveAddList(DeliverAddressListReponse response) {
        llytAddressContainer.removeAllViews();

        if (receiveAddressItemHolders == null) {
            receiveAddressItemHolders = new ArrayList<>();
        } else {
            receiveAddressItemHolders.clear();
        }
        final int modeSize = response.getDeliverAddressModelList().size();
        for (int i = 0; i < modeSize; i++) {
            // 实例化收货地址列表item视图
            final View convertStoreView = layoutInflater.inflate(R.layout.layout_my_address_item, null);
            final ReceiveAddressItemHolder itemHolder = findStoreItemView(convertStoreView);
            String defauValue = response.getDeliverAddressModelList().get(i).getIsDefault();

            if (defauValue.equals("0")) {
                itemHolder.setDefauReceive.setText(getResources().getString(R.string.default_address));
                itemHolder.setDefauReceive.setTextColor(getResources().getColor(R.color.order_coupon_txt_cg));
                itemHolder.setDefauReceiveImg.setVisibility(View.VISIBLE);
                itemHolder.deleteReceive.setTextColor(getResources().getColor(R.color.order_coupon_txt_cg));
                convertStoreView.setBackgroundColor(getResources().getColor(R.color.invoice_not_checked));
                //
            } else {
                itemHolder.setDefauReceive.setText(getResources().getString(R.string.set_default_address));
                itemHolder.setDefauReceive.setTextColor(getResources().getColor(R.color.black));
                itemHolder.deleteReceive.setTextColor(getResources().getColor(R.color.black));
                itemHolder.setDefauReceiveImg.setVisibility(View.GONE);
            }
            itemHolder.receiveName.setText(response.getDeliverAddressModelList().get(i).getDeliverPerson());
            itemHolder.receiveTel.setText(response.getDeliverAddressModelList().get(i).getDeliverMobile());
            String str = response.getDeliverAddressModelList().get(i).getAreaProvinceName()
                    + response.getDeliverAddressModelList().get(i).getAreaCityName()
                    + response.getDeliverAddressModelList().get(i).getAreaDistrictName()
                    + response.getDeliverAddressModelList().get(i).getAddressDetail();
            itemHolder.receiveAdd.setText(str);
            itemHolder.editReceive.setOnClickListener(this);
            itemHolder.editReceive.setTag(i);
            itemHolder.deleteReceive.setOnClickListener(this);
            itemHolder.deleteReceive.setTag(i);
            itemHolder.setDefauReceive.setOnClickListener(this);
            itemHolder.setDefauReceive.setTag(i);
            convertStoreView.setTag(i);

            receiveAddressItemHolders.add(itemHolder);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, 0, 15);
            llytAddressContainer.addView(convertStoreView, lp);
        }
    }

    /**
     * 有收货地址
     */
    private void showHasDataView() {
        llytHasData.setVisibility(View.VISIBLE);
        llytNoData.setVisibility(View.GONE);

    }

    /**
     * 无收货地址
     */
    private void showNoDataView() {
        llytHasData.setVisibility(View.GONE);
        llytNoData.setVisibility(View.VISIBLE);

    }

    /**
     * get ReceiveAddressItemHolder by spec view container
     */
    private ReceiveAddressItemHolder findStoreItemView(View convertView) {
        ReceiveAddressItemHolder holder = new ReceiveAddressItemHolder();
        holder.setDefauReceive = (TextView) convertView.findViewById(R.id.setDefauReceive);
        holder.receiveTel = (TextView) convertView.findViewById(R.id.receiveTel);
        holder.receiveName = (TextView) convertView.findViewById(R.id.receiveName);
        holder.receiveAdd = (TextView) convertView.findViewById(R.id.receiveCity);
        holder.editReceive = (TextView) convertView.findViewById(R.id.editReceive);
        holder.deleteReceive = (TextView) convertView.findViewById(R.id.deleteReceive);

        holder.deleteReceive.setOnClickListener(this);
        holder.setDefauReceiveImg = (ImageView) convertView.findViewById(R.id.setDefauReceiveImg);
        return holder;
    }
}